﻿#include "TextFileParser.h"
#include <QDebug>
#include <QTime>
#include <QPair>
#include <QVector>
#include <QString>
#include <vtkTable.h>
#include <vtkPoints.h>
#include <vtkSys/SystemTools.hxx>
#include <vtkDelimitedTextReader.h>
#include <vtkAbstractArray.h>
#include <vtkDoubleArray.h>
#include <vtkVariantArray.h>
#include <fstream>
#include <sstream>
#include <iostream>
#include <vtkStringArray.h>
#include <vtkFieldData.h>
#include <vtkDelimitedTextWriter.h>

#include "BaseModule/IBaseSignal.h"
#include "BaseModule/GlobalHelper.h"
#include "CommonFunction.h"
#include "TextArrayMetaHander.h"

namespace
{
    void permutationHelper(QVector<QVector<double>>& result,
                           QVector<double>& tempList, QVector<QVector<double>>& inputLists, int depth)
    {
        if (tempList.size() == inputLists.size())
        {
            result.push_back(tempList);
            return;
        }

        for (int i = 0; i < inputLists[depth].size(); i++)
        {
            tempList.push_back(inputLists[depth][i]);
            permutationHelper(result, tempList, inputLists, depth + 1);
            tempList.pop_back();
        }
    }

    QVector<QVector<double>> permutation(QVector<QVector<double>>& inputLists)
    {
        QVector<QVector<double>> result;
        QVector<double> tempList;
        permutationHelper(result, tempList, inputLists, 0);
        return result;
    }
} // namespace

namespace pst
{
    TextFileParser::TextFileParser(QObject* parent)
        : QObject(parent),
          // m_fileName(),
          m_originalTable(nullptr),
          m_eachColNameOfKey(),
          m_eachColUnitOfKey(),
          m_eachColDataOfKey(),
          m_keyLenth(0),
          m_eachColNameOfValue(),
          m_eachColUnitOfValue(),
          m_eachColDataOfValue(),
          m_valueLenth(0),
          m_valueMatrix(),
          m_isSetLog{false},
          m_isSetNormalized{false},
          m_logFactory{10.},
          m_scanParaIndex{-1},
          m_chosenKeyList{},
          m_chosenDataTable(vtkTable::New()),
          m_errorMessage(),
          m_fileDealType(-1),
          m_fileComponentType(-1),
          m_standardTable(vtkSmartPointer<vtkTable>::New())
    {
    }

    TextFileParser::~TextFileParser()
    {
        m_chosenDataTable->Delete();
    }

    void TextFileParser::SetFileName(const QString& fileName)
    {
        m_fileName = fileName;
    }

    QString TextFileParser::GetFileName()
    {
        return m_fileName;
    }

    void TextFileParser::SetInputTable(vtkTable* table)
    {
        m_originalTable = table;
    }

    vtkTable* TextFileParser::GetInputTable()
    {
        return m_originalTable;
    }

    void TextFileParser::setFileDealType(int type)
    {
        m_fileDealType = type;
    }

    int TextFileParser::getFileDealType()
    {
        return m_fileDealType;
    }

    void TextFileParser::setFileComponentType(int type)
    {
        m_fileComponentType = type;
    }

    int TextFileParser::getFileComponentType()
    {
        return m_fileComponentType;
    }

    // vtkDelimitedTextReader* TextFileParser::getTextReader()
    //{
    //     return m_reader;
    // }

    bool TextFileParser::Update()
    {

        if (m_originalTable == nullptr)
        {
            return false;
        }

        // m_fileDealType = 1; // 测试

        // if (m_fileDealType == 0) // 常规文件处理方式，不扩展
        //{
        //     clearData();
        //     if (!parseTitleName(m_originalTable, m_eachColNameOfKey, m_eachColUnitOfKey,
        //         m_eachColNameOfValue, m_eachColUnitOfValue))
        //     {
        //         return false;
        //     }
        //     m_expandedTable = m_originalTable;
        //     m_eachColGroupNameOfValue = m_eachColNameOfValue;
        // }
        // else // 需要扩展
        //{
        //     if (!expandTable())
        //     {
        //         return false;
        //     }
        clearData();
        if (!parseTitleName(m_originalTable, m_eachColNameOfKey, m_eachColUnitOfKey,
                            m_eachColNameOfValue, m_eachColUnitOfValue))
        {
            return false;
        }
        //}

        // vtkNew<vtkDelimitedTextWriter> writer;

        // qDebug() << "TextFileParser.table = ";
        // m_originalTable->Print(std::cout);
        // QString fre = "D:/m_originalTable.txt";
        // writer->SetFileName(fre.toStdString().c_str());
        // writer->SetInputData(m_originalTable);
        // writer->Write();

        // qDebug() << "Text read file end" << QTime::currentTime();

        m_keyLenth = m_eachColNameOfKey.size();
        m_valueLenth = m_eachColNameOfValue.size();
        return generateValueMatrix();
    }

    vtkSmartPointer<vtkTable> TextFileParser::getStandardTable()
    {
        return m_standardTable;
    }

    void TextFileParser::SetLogTheData(bool log)
    {
        m_isSetLog = log;
    }

    bool TextFileParser::GetLogTheData()
    {
        return m_isSetLog;
    }

    void TextFileParser::SetNormalizeTheData(bool normolized)
    {
        m_isSetNormalized = normolized;
    }

    bool TextFileParser::GetNormalizeTheData()
    {
        return m_isSetNormalized;
    }

    void TextFileParser::SetLogCoefficients(double factory)
    {
        m_logFactory = factory;
    }

    double TextFileParser::GetLogFactory()
    {
        return m_logFactory;
    }

    vtkTable* TextFileParser::getOriginalTable()
    {
        return m_originalTable;
    }

    QVector<QString> TextFileParser::getEachColNameOfKey()
    {
        return m_eachColNameOfKey;
    }

    QVector<QString> TextFileParser::getEachColUnitOfKey()
    {
        return m_eachColUnitOfKey;
    }

    QVector<QVector<double>> TextFileParser::getEachColDataOfKey()
    {
        return m_eachColDataOfKey;
    }

    QVector<QString> TextFileParser::getEachColGroupNameOfValue()
    {
        return m_eachColGroupNameOfValue;
    }

    QVector<QString> TextFileParser::getEachColNameOfValue()
    {
        return m_eachColNameOfValue;
    }

    QVector<QString> TextFileParser::getEachColUnitOfValue()
    {
        return m_eachColUnitOfValue;
    }

    QVector<QVector<double>> TextFileParser::getEachColDataOfValue()
    {
        return m_eachColDataOfValue;
    }

    QHash<QVector<double>, QVector<double>> TextFileParser::getValueMatrix()
    {
        return m_valueMatrix;
    }

    void TextFileParser::setScanParameterIndex(int index)
    {
        m_scanParaIndex = index;
    }

    int TextFileParser::getScanParameterIndex()
    {
        return m_scanParaIndex;
    }

    void TextFileParser::setOtherKeyParameter(const QVector<QVector<double>>& keyParaList)
    {
        m_chosenKeyList = keyParaList;
    }

    QVector<QVector<double>> TextFileParser::getOtherKeyParameter()
    {
        return m_chosenKeyList;
    }

    void TextFileParser::getChosenLinesFromKey(QList<int> valueId, vtkTable* returnTable)
    {
        // 给每个表格添加自变量列，即扫描参数列
        // auto scanArray = m_originalTable->GetColumn(m_scanParaIndex);//扫描参数列
        vtkNew<vtkDoubleArray> scanArray;
        QVector<double> scanList = m_eachColDataOfKey[m_scanParaIndex];
        scanArray->SetName(m_eachColNameOfKey[m_scanParaIndex].toStdString().c_str());
        for (int i = 0; i < scanList.size(); ++i)
        {
            scanArray->InsertNextTuple1(scanList[i]);
        }

        returnTable->RemoveAllColumns();   // 置空
        returnTable->AddColumn(scanArray); // 扫描参数列作为自变量,第0列

        QVector<QVector<double>> keyList = permutation(m_chosenKeyList);
        // m_chosenDataTable->(keyList.size() + 1);//第0列为自变量，其他列为因变量

        // 每次循环产生valueId.size条曲线
        for (int i = 0; i < keyList.size(); ++i)
        {
            QVector<double> temp = keyList[i]; // 除扫描参数外，其他的key构成的list，取一个具体的key

            // 选择了查看几个value列，就产生多少个列
            QList<vtkSmartPointer<vtkDoubleArray>> tempArrayList;
            for (int m = 0; m < valueId.size(); ++m)
            {
                vtkNew<vtkDoubleArray> lineArray;
                tempArrayList.append(lineArray);
            }

            // 组合生成曲线名字
            QString arrayName{};
            // arrayName += va //value列的名字
            for (int nameIndex = 0, j = 0; nameIndex < m_eachColNameOfKey.size(); ++nameIndex, ++j)
            {
                if (nameIndex == m_scanParaIndex)
                {
                    --j;
                    continue;
                }
                arrayName += QString(m_eachColNameOfKey[nameIndex]) + "=" + QString::number(temp[j]) + " ";
            }
            // lineArray->SetName(arrayName.toStdString().c_str()); //列名 根据temp获取

            for (int k = 0; k < scanArray->GetNumberOfTuples(); ++k)
            {
                QVector<double> temp = keyList[i]; // 除扫描参数外，其他的key构成的list，取一个具体的key

                temp.insert(m_scanParaIndex, scanArray->GetVariantValue(k).ToDouble()); // 一个完整的Key
                auto value = m_valueMatrix.value(temp);                                 // 对应的值
                // 可能取不到值 会报错
                for (int m = 0; m < valueId.size(); ++m)
                {
                    tempArrayList[m]->InsertNextTuple1(value[valueId[m]]);
                }
            }

            for (int m = 0; m < valueId.size(); ++m)
            {
                auto _tempArrayName = arrayName;
                _tempArrayName += m_eachColNameOfValue[valueId[m]];
                tempArrayList[m]->SetName(_tempArrayName.toStdString().c_str()); // 列名 根据temp获取
                returnTable->AddColumn(tempArrayList[m]);
            }
        }
        // 生成m个vtkTable,每个table中，第一列是自变量（扫描参数），其他列为对应的因变量数值，每列为一条曲线
    }

    void TextFileParser::getChosenLinesFromKey(QList<QPair<int, int>> valueId,
                                               QList<Info2DPointer>& yList)
    {
        yList.clear();
        QVector<QVector<double>> keyList = permutation(m_chosenKeyList);

        for (int i = 0; i < keyList.size(); ++i)
        {
            QVector<double> temp = keyList[i]; // 除扫描参数外，其他的key构成的list，取一个具体的key

            QList<Info2DPointer> tempValueList;
            for (int i = 0; i < valueId.size(); i++) // 分配存储空间
            {
                Info2DPointer info = Info2DPointer::create();
                info->setXData(qMakePair(m_eachColNameOfKey[m_scanParaIndex], m_eachColDataOfKey[m_scanParaIndex]));
                info->setScanParameterIndex(m_scanParaIndex);
                info->setOtherKeyData(temp);
                info->setReader(this);
                info->setGeometryFileName(this->m_geometryFileName);
                tempValueList.append(info);
            }

            // 组合生成曲线名字
            QString arrayName{};
            // arrayName += va //value列的名字
            for (int nameIndex = 0, j = 0; nameIndex < m_eachColNameOfKey.size(); ++nameIndex, ++j)
            {
                if (nameIndex == m_scanParaIndex)
                {
                    --j;
                    continue;
                }
                arrayName += QString(m_eachColNameOfKey[nameIndex]) + "=" + QString::number(temp[j]) + " ";
            }

            for (int k = 0; k < m_eachColDataOfKey[m_scanParaIndex].size(); ++k)
            {
                QVector<double> temp = keyList[i]; // 除扫描参数外，其他的key构成的list，取一个具体的key

                temp.insert(m_scanParaIndex, m_eachColDataOfKey[m_scanParaIndex][k]); // 一个完整的Key
                auto value = m_valueMatrix.value(temp);                               // 对应的值
                // 可能取不到值 会报错
                for (int m = 0; m < valueId.size(); ++m)
                {
                    int realValueIndex = getRealValueIndex(valueId[m].first, valueId[m].second);
                    tempValueList[m]->getYDataPointer()->second.append(value[realValueIndex]);
                    tempValueList[m]->setValueIndex(valueId[m].first);
                }
            }

            for (int m = 0; m < valueId.size(); ++m)
            {
                auto _tempArrayName = arrayName;
                int realValueIndex = getRealValueIndex(valueId[m].first, valueId[m].second);
                _tempArrayName += m_eachColNameOfValue[realValueIndex];
                //_tempArrayName += m_eachColGroupNameOfValue[valueId[m].first];
                tempValueList[m]->getYDataPointer()->first = _tempArrayName; // 列名 根据temp获取
                yList.append(tempValueList[m]);
            }
        }
    }

    void TextFileParser::getChosenLinesFromMultiKey(QList<QPair<int, int>> valueId, QList<Info2DPointer>& yList)
    {
        yList.clear();
        QVector<QVector<double>> keyList = permutation(m_chosenKeyList);

        for (int i = 0; i < keyList.size(); ++i)
        {
            QVector<double> temp = keyList[i]; // 除扫描参数外，其他的key构成的list，取一个具体的key

            QList<Info2DPointer> tempValueList;
            for (int i = 0; i < valueId.size(); i++) // 分配存储空间
            {
                Info2DPointer info = Info2DPointer::create();
                info->setXData(qMakePair(m_eachColNameOfKey[m_scanParaIndex], m_eachColDataOfKey[m_scanParaIndex]));
                info->setScanParameterIndex(m_scanParaIndex);
                info->setSecondScanParameterIndex(m_secondScanParaIndex);
                info->setOtherKeyData(temp);
                info->setReader(this);
                info->setGeometryFileName(this->m_geometryFileName);
                tempValueList.append(info);
            }

            // 组合生成曲线名字
            QString arrayName{};
            // arrayName += va //value列的名字
            for (int nameIndex = 0, j = 0; nameIndex < m_eachColNameOfKey.size(); ++nameIndex, ++j)
            {
                if (nameIndex == m_scanParaIndex || nameIndex == m_secondScanParaIndex)
                {
                    --j;
                    continue;
                }
                arrayName += QString(m_eachColNameOfKey[nameIndex]) + "=" + QString::number(temp[j]) + " ";
            }

            for (int k = 0; k < m_eachColDataOfKey[m_scanParaIndex].size(); ++k)
            {
                for (int l = 0; l < m_eachColDataOfKey[m_secondScanParaIndex].size(); ++l)
                {
                    QVector<double> keyArray = keyList[i]; // 除扫描参数外，其他的key构成的list，取一个具体的key
                    QVector<double> temp(m_keyLenth);
                    for (int index = 0; index < temp.size(); ++index)
                    {
                        if (index == m_scanParaIndex)
                        {
                            temp[index] = m_eachColDataOfKey[m_scanParaIndex][k];
                        }
                        else if (index == m_secondScanParaIndex)
                        {
                            temp[index] = m_eachColDataOfKey[m_secondScanParaIndex][l];
                        }
                        else
                        {
                            temp[index] = keyArray.takeFirst();
                        }
                    }

                    auto value = m_valueMatrix.value(temp); // 对应的值
                    // 可能取不到值 会报错
                    for (int m = 0; m < valueId.size(); ++m)
                    {
                        int realValueIndex = getRealValueIndex(valueId[m].first, valueId[m].second);
                        tempValueList[m]->getYDataPointer()->second.append(value[realValueIndex]);
                        tempValueList[m]->setValueIndex(valueId[m].first);
                    }
                }
            }

            for (int m = 0; m < valueId.size(); ++m)
            {
                auto _tempArrayName = arrayName;
                int realValueIndex = getRealValueIndex(valueId[m].first, valueId[m].second);
                _tempArrayName += m_eachColNameOfValue[realValueIndex];
                tempValueList[m]->getYDataPointer()->first = _tempArrayName; // 列名 根据temp获取
                yList.append(tempValueList[m]);
            }
        }
    }

    // 应需求：每条曲线先归一化，再取对数，再转直角坐标。都是对单条曲线自身的操作
    void TextFileParser::getChosenPointsListFromKey(QList<int> valueId,
                                                    QList<vtkSmartPointer<vtkPoints>>& resultPointsList, QList<vtkSmartPointer<vtkPoints>>& resultPointsList_sphere,
                                                    QList<QString>& lineName, double radiusBestRange[2], bool log, bool normalize, double minValueWanted, bool enableCustomRange)
    {
        vtkNew<vtkDoubleArray> scanArray;
        QVector<double> scanList = m_eachColDataOfKey[m_scanParaIndex];
        scanArray->SetName(m_eachColNameOfKey[m_scanParaIndex].toStdString().c_str());
        for (int i = 0; i < scanList.size(); ++i)
        {
            scanArray->InsertNextTuple1(scanList[i]); // 每一个扫描参数列 /theta = 0 , theta = 1, theta = 2 ...
        }

        QVector<QVector<double>> keyList = permutation(m_chosenKeyList);
        // m_chosenDataTable->(keyList.size() + 1);//第0列为自变量，其他列为因变量

        QVector<QVector<QVector<double>>> allCurvesMinMaxValueList;

        // 获取所有曲线归一化取对数后的最小最大值 begin
        // 获取所有曲线归一化取对数后的最小最大值 begin
        // 获取所有曲线归一化取对数后的最小最大值 begin
        double chosenCurveMinValue = VTK_DOUBLE_MAX;  // 全局最值
        double chosenCurveMaxValue = -VTK_DOUBLE_MAX; // 全局最值

        for (int i = 0; i < keyList.size(); ++i)
        {
            // 选择了查看几个value列，就产生多少个列
            QVector<QVector<double>> LineValueList; // 取出每一个key对应的valueList  QList<"value1", "value2", "value3">

            for (int k = 0; k < scanArray->GetNumberOfTuples(); ++k)
            {
                QVector<double> tempKeys = keyList[i];                                      // 除扫描参数外，其他的key构成的list，取一个具体的key
                tempKeys.insert(m_scanParaIndex, scanArray->GetVariantValue(k).ToDouble()); // 一个完整的Key
                auto valueList = m_valueMatrix.value(tempKeys);                             // 对应的多个value值

                LineValueList.append(valueList);
            }

            if (LineValueList.empty())
            {
                return;
            }

            QVector<QVector<double>> minMaxValueList;
            for (int i = 0; i < valueId.size(); ++i) // 按列取，取出 "value1", "value2", "value3"
            {
                // 每一列值 如"value1"， "value2"， "value3"
                double minValue = VTK_DOUBLE_MAX;
                double maxValue = -VTK_DOUBLE_MAX;
                for (int j = 0; j < LineValueList.size(); ++j)
                {
                    if (LineValueList[j][i] > maxValue)
                    {
                        maxValue = LineValueList[j][i];
                    }
                    if (LineValueList[j][i] < minValue)
                    {
                        minValue = LineValueList[j][i];
                    }
                }
                minMaxValueList.append({minValue, maxValue});
            }
            allCurvesMinMaxValueList.append(minMaxValueList);

            // 计算全局最值
            if (!normalize && !log) // 及不取对数也不归一化，使用原始值
            {
                for (int i = 0; i < minMaxValueList.size(); ++i)
                {
                    if (minMaxValueList[i][0] < chosenCurveMinValue)
                    {
                        chosenCurveMinValue = minMaxValueList[i][0];
                    }
                    if (minMaxValueList[i][1] > chosenCurveMaxValue)
                    {
                        chosenCurveMaxValue = minMaxValueList[i][1];
                    }
                }
            }
            else if (normalize && !log) // 只归一化
                                        // 每条曲线归一化，除以自己的最大值
            {
                for (int i = 0; i < minMaxValueList.size(); ++i)
                {
                    if (minMaxValueList[i][0] / minMaxValueList[i][1] < chosenCurveMinValue)
                    {
                        chosenCurveMinValue = minMaxValueList[i][0] / minMaxValueList[i][1];
                    }
                }
                chosenCurveMaxValue = 1;
            }
            else if (!normalize && log) // 只取对数
            {
                for (int i = 0; i < minMaxValueList.size(); ++i)
                {
                    auto logMinValue = 10 * std::log10(minMaxValueList[i][0]);
                    auto logMaxValue = 10 * std::log10(minMaxValueList[i][1]);
                    if (logMinValue < chosenCurveMinValue)
                    {
                        chosenCurveMinValue = logMinValue;
                    }
                    if (logMaxValue > chosenCurveMaxValue)
                    {
                        chosenCurveMaxValue = logMaxValue;
                    }
                }
            }
            else // 既归一化，又取对数
                 // 先归一化，再取对数
            {
                for (int i = 0; i < minMaxValueList.size(); ++i)
                {
                    auto minV = 10 * std::log10(minMaxValueList[i][0] / minMaxValueList[i][1]);
                    if (minV < chosenCurveMinValue)
                    {
                        chosenCurveMinValue = minV;
                    }
                }
                chosenCurveMaxValue = 0;
            }
        }
        // 获取所有曲线归一化取对数后的最小最大值 end
        // 获取所有曲线归一化取对数后的最小最大值 end
        // 获取所有曲线归一化取对数后的最小最大值 end

        radiusBestRange[0] = chosenCurveMinValue;
        radiusBestRange[1] = chosenCurveMaxValue;

        // 每次循环产生valueId.size条曲线
        for (int i = 0; i < keyList.size(); ++i)
        {
            QVector<double> temp = keyList[i]; // 除扫描参数外，其他的key构成的list，取一个具体的key

            // 选择了查看几个value列，就产生多少个列
            QList<vtkSmartPointer<vtkPoints>> tempArrayList;
            QList<vtkSmartPointer<vtkPoints>> tempArrayList_sphere;
            for (int m = 0; m < valueId.size(); ++m)
            {
                vtkNew<vtkPoints> lineArray;
                tempArrayList.append(lineArray);
                vtkNew<vtkPoints> lineArray_sphere;
                tempArrayList_sphere.append(lineArray_sphere);
            }

            // 组合生成曲线名字
            QString arrayName{};
            for (int nameIndex = 0, j = 0; nameIndex < m_eachColNameOfKey.size(); ++nameIndex, ++j)
            {
                if (nameIndex == m_scanParaIndex)
                {
                    --j;
                    continue;
                }
                arrayName += QString(m_eachColNameOfKey[nameIndex]) + "=" + QString::number(temp[j]) + " ";
            }

            QVector<QVector<double>> lineKeyList;   // 每一个完整的key  QList<"key1", "key2", "key3">
            QVector<QVector<double>> LineValueList; // 取出每一个key对应的valueList  QList<"value1", "value2", "value3">

            for (int k = 0; k < scanArray->GetNumberOfTuples(); ++k)
            {
                QVector<double> tempKeys = keyList[i];                                      // 除扫描参数外，其他的key构成的list，取一个具体的key
                tempKeys.insert(m_scanParaIndex, scanArray->GetVariantValue(k).ToDouble()); // 一个完整的Key
                auto valueList = m_valueMatrix.value(tempKeys);                             // 对应的多个value值

                lineKeyList.append(tempKeys);
                LineValueList.append(valueList);
            }

            // 找出每一列value的最大最小值
            QVector<QVector<double>> minMaxValueList = allCurvesMinMaxValueList[i];       // 没有取对数、归一化
            QVector<QVector<double>> minMaxValueListNorLog = allCurvesMinMaxValueList[i]; // 取对数、归一化后的数据

            if (LineValueList.empty())
            {
                return;
            }

            // 每一列值归一化、取对数、平移、转直角坐标
            for (int i = 0; i < valueId.size(); ++i) // 按列取，取出 "value1", "value2", "value3"
            {
                // 对最值进行归一化取对数
                if (normalize)
                {
                    minMaxValueListNorLog[i][0] = minMaxValueListNorLog[i][0] / minMaxValueListNorLog[i][1]; // 最小值进行归一化
                    minMaxValueListNorLog[i][1] = 1;
                }
                if (log)
                {
                    minMaxValueListNorLog[i][0] = 10 * std::log10(minMaxValueListNorLog[i][0]); // 最小值进行取对数
                    minMaxValueListNorLog[i][1] = 10 * std::log10(minMaxValueListNorLog[i][1]); // 最大值进行取对数
                }

                /// 处理数据
                for (int j = 0; j < LineValueList.size(); ++j)
                {
                    // 每一列值 如"value1"， "value2"， "value3"
                    if (normalize) // 归一化
                    {
                        if (qFuzzyCompare(minMaxValueList[i][1], 0.))
                        {
                            m_errorMessage = "Max value is zero while nomalizing the data! \n";
                            continue;
                        }
                        // LineValueList[j][i] = (LineValueList[j][i] - minMaxValueList[i][0]) / (minMaxValueList[i][1] - minMaxValueList[i][0]);//归一化到0-1版本
                        LineValueList[j][i] = LineValueList[j][i] / minMaxValueList[i][1]; // 直接除以最大值版本
                    }

                    if (log) // 取对数
                    {
                        LineValueList[j][i] = 10 * std::log10(LineValueList[j][i]);
                    }

                    auto lineValue = LineValueList[j][i]; // 用于转直角坐标系画图

                    //  计算新的数据范围 , lineValue此时是>=0的
                    if (enableCustomRange)
                    {
                        if (minMaxValueListNorLog[i][0] >= minValueWanted) // 当前曲线最小值比想要的最小值大（或等），减去最小值
                        {
                            lineValue -= minValueWanted; // 大减小 必为正(或0)
                        }
                        else // 曲线最小值比想要的最小值更小
                        {
                            lineValue = std::max(lineValue, minValueWanted);
                            lineValue -= minValueWanted;
                        }
                    }
                    else
                    {
                        if (chosenCurveMinValue < 0) // 与全局最小值比较
                        {
                            lineValue -= chosenCurveMinValue;
                        }
                    }

                    // 转直角坐标
                    double x{0.0};
                    double y{0.0};
                    double z{0.0};
                    //"Theta||deg||key","Phi||deg||key","Frequency||GHz||key","Gain||None||value"
                    // LineValueList[j][i] 为R
                    if (m_scanParaIndex == 1) // theta
                    {
                        CommonFunction::PolarToRectangularCoorSys(lineKeyList[j][1], lineValue, x, y);
                    }
                    else if (m_scanParaIndex == 0) // phi
                    {
                        CommonFunction::PolarToRectangularCoorSys(lineKeyList[j][0], lineValue, x, y);
                    }

                    tempArrayList[i]->InsertNextPoint(x, y, 0);
                    tempArrayList_sphere[i]->InsertNextPoint(lineKeyList[j][0], lineKeyList[j][1], LineValueList[j][i]); // 数据操作后的原始值,用于拾取
                }
            }

            for (int m = 0; m < valueId.size(); ++m)
            {
                auto _tempArrayName = arrayName;
                _tempArrayName += m_eachColNameOfValue[valueId[m]];

                lineName.append(_tempArrayName);

                resultPointsList.append(tempArrayList[m]);
                resultPointsList_sphere.append(tempArrayList_sphere[m]);
            }
        }
    }

    QString TextFileParser::getErrorMessage() const
    {
        return m_errorMessage;
    }

    // bool TextFileParser::ReadTxtToVTKTable(const QString& filename)
    //{
    //     qDebug() << "ReadTxtToVTKTable =  " << filename;
    //     m_originalTable = vtkSmartPointer<vtkTable>::New();

    //    QFile file(filename);

    //    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    //    {
    //        emit IBaseSignalInstance->signal_sendErrorMessageToUI("错误，无法打开文件：" + filename);
    //        return false;
    //    }

    //    QTextStream in(&file);
    //    QStringList columnNames;

    //    int lineNumber = 0;
    //    while (!in.atEnd())
    //    {
    //        QString line = in.readLine();

    //        // Skip the first line (could be a header)
    //        if (lineNumber == 0)
    //        {
    //            m_textHeaderComment = line;
    //            lineNumber++;
    //            continue;
    //        }

    //        // Remove '#' and leading spaces from the second line
    //        if (lineNumber == 1)
    //        {
    //            m_textHeader = line;
    //            line.remove(0, line.indexOf(QRegExp("[^#\\s]"))); // Remove leading '#' and spaces
    //            columnNames = line.split(',', QString::SkipEmptyParts);
    //            for (const QString& colName : columnNames)
    //            {
    //                auto array = vtkSmartPointer<vtkDoubleArray>::New();
    //                array->SetName(colName.toStdString().c_str());
    //                m_originalTable->AddColumn(array);
    //            }
    //            lineNumber++;
    //            continue;
    //        }

    //        // Read data lines
    //        QStringList values = line.split(',', QString::SkipEmptyParts);

    //        if (values.size() != columnNames.size())
    //        {
    //            emit IBaseSignalInstance->signal_sendErrorMessageToUI("错误，格式错误，行号：" + QString::number(lineNumber));

    //            return false;
    //        }

    //        vtkNew<vtkVariantArray> rowData;
    //        for (vtkIdType col = 0; col < values.size(); col++)
    //        {
    //            auto value = values.at(col).toDouble();
    //            rowData->InsertNextValue(value);
    //        }
    //        m_originalTable->InsertNextRow(rowData);
    //        lineNumber++;
    //    }

    //    vtkNew<vtkStringArray> annotations;
    //    annotations->SetName("HeadComment");
    //    annotations->SetNumberOfValues(1);
    //    annotations->SetValue(0, m_textHeaderComment.toStdString().c_str());
    //    m_originalTable->GetFieldData()->AddArray(annotations);

    //    vtkNew<vtkStringArray> headerText;
    //    headerText->SetName("Header");
    //    headerText->SetNumberOfValues(1);
    //    headerText->SetValue(0, m_textHeader.toStdString().c_str());
    //    m_originalTable->GetFieldData()->AddArray(headerText);

    //    file.close();
    //    return true;
    //}

    TextArrayMetaStruct TextFileParser::getDataInfo(int valueIndex)
    {
        TextArrayMetaStruct metaStruct;
        if (valueIndex > m_eachColGroupNameOfValue.size() || valueIndex == m_eachColGroupNameOfValue.size() || valueIndex < 0)
            return metaStruct;
        const auto& name = m_eachColGroupNameOfValue.at(valueIndex);

        for (int i = 0; i < m_originalTable->GetNumberOfColumns(); ++i)
        {
            auto colData = m_originalTable->GetColumn(i);

            bool isSuc = TextArrayMetaHander::getArrayMeta(colData, metaStruct);
            if (!isSuc)
            {
                qDebug() << "获取meta失败";
                continue;
            }
            if (metaStruct.dataGroupName == name)
            {
                break;
            }
        }
        return metaStruct;
    }

    TextArrayMetaStruct TextFileParser::getDataInfoByRealValueIndex(int valueIndex)
    {
        TextArrayMetaStruct metaStruct;
        if (valueIndex >= m_eachColNameOfValue.size())
        {
            qDebug() << "获取meta失败";
            return metaStruct;
        }
        auto colData = m_originalTable->GetColumn(valueIndex + m_eachColDataOfKey.size());
        bool isSuc = TextArrayMetaHander::getArrayMeta(colData, metaStruct);
        if (!isSuc)
        {
            qDebug() << "获取meta失败";
        }
        return metaStruct;
    }

    bool TextFileParser::parseTitleName(vtkTable* inputTable,
                                        QVector<QString>& eachColNameOfKey, QVector<QString>& eachColUnitOfKey,
                                        QVector<QString>& eachColNameOfValue, QVector<QString>& eachColUnitOfValue)
    {
        if (inputTable == nullptr)
        {
            m_errorMessage = "inputTable is null!";
            return false;
        }

        for (int i = 0; i < inputTable->GetNumberOfColumns(); ++i)
        {
            QString arrayName = QString(inputTable->GetColumn(i)->GetName()).trimmed();
            QStringList splitList = arrayName.split("||", QString::SkipEmptyParts);
            if (splitList.size() != 3)
            {
                // qDebug() << " Warning! File format illegal : " << m_fileName;
                m_errorMessage = "File format illegal!";
                return false;
            }

            // 判断是key还是value
            QString type = splitList[2].trimmed();
            if (type.toUpper() == "KEY")
            {
                eachColNameOfKey.append(splitList[0]);
                eachColUnitOfKey.append(splitList[1]);
            }
            else if (type.toUpper() == "VALUE")
            {
                eachColNameOfValue.append(splitList[0]);
                eachColUnitOfValue.append(splitList[1]);

                if (m_fileComponentType == 0)
                {
                    m_eachColGroupNameOfValue.append(splitList[0]);
                }
                else
                {
                    auto colData = inputTable->GetColumn(i);

                    TextArrayMetaStruct metaStruct;
                    bool isSuc = TextArrayMetaHander::getArrayMeta(colData, metaStruct);
                    if (!isSuc)
                    {
                        qDebug() << "获取meta失败";
                        return false;
                    }
                    // if ((i - eachColNameOfKey.size()) % 4 == 0)
                    //{
                    //     m_eachColGroupNameOfValue.append(metaStruct.dataGroupName);
                    // }
                    if (!m_eachColGroupNameOfValue.contains(metaStruct.dataGroupName))
                    {
                        m_eachColGroupNameOfValue.append(metaStruct.dataGroupName);
                    }
                }
            }
            else
            {
                // qDebug() << " Warning! File format illegal, type is " << type << " in " << m_fileName;
                m_errorMessage = "File format illegal, type is " + type;
                return false;
            }
        }

        return true;
    }

    void TextFileParser::clearData()
    {
        m_eachColNameOfKey.clear();
        m_eachColUnitOfKey.clear();
        m_eachColDataOfKey.clear();
        m_eachColNameOfValue.clear();
        m_eachColUnitOfValue.clear();
        m_eachColDataOfValue.clear();
        m_valueMatrix.clear();
        m_keyLenth = 0;
        m_valueLenth = 0;
    }

    bool TextFileParser::generateValueMatrix()
    {
        m_valueMatrix.clear();
        m_standardTable->DeepCopy(m_originalTable);
        // qDebug() << "generateValueMatrix function ====================begin ==============" << QTime::currentTime();
        for (int i = 0; i < m_keyLenth; ++i)
        {
            m_eachColDataOfKey.append(QVector<double>());
        }
        for (int i = 0; i < m_valueLenth; ++i)
        {
            m_eachColDataOfValue.append(QVector<double>());
        }

        for (int i = 0; i < m_originalTable->GetNumberOfRows(); ++i) // 多线程
        {
            QVector<double> keyList;
            QVector<double> valueList;
            for (int j = 0; j < m_keyLenth; ++j) // 每一行的所有key列
            {
                bool isSuc = false;
                auto value = m_originalTable->GetValue(i, j).ToDouble(&isSuc);
                if (!isSuc)
                {
                    m_errorMessage = "File format illegal, data contains nonnumerical value ";
                    return false;
                }
                QString unit = m_eachColUnitOfKey.at(j).toLower().trimmed();
                UnitConversion(unit, value);
                m_standardTable->SetValue(i, j, value); // 保存标准化后的数据
                keyList.append(value);
                if (!m_eachColDataOfKey[j].contains(value))
                {
                    m_eachColDataOfKey[j].append(value);
                }
            }
            for (int j = m_keyLenth; j < m_originalTable->GetNumberOfColumns(); ++j) // 每一行的所有value列
            {
                bool isSuc = false;
                auto value = m_originalTable->GetValue(i, j).ToDouble(&isSuc);
                if (!isSuc)
                {
                    m_errorMessage = "File format illegal, data contains nonnumerical value ";
                    return false;
                }
                QString unit = m_eachColUnitOfValue.at(j - m_keyLenth).toLower().trimmed();
                UnitConversion(unit, value);
                m_standardTable->SetValue(i, j, value); // 保存标准化后的数据
                valueList.append(value);
                m_eachColDataOfValue[j - m_keyLenth].append(value);
            }
            m_valueMatrix.insert(keyList, valueList);
        }

        UnitChange();
        changeMetaUnit(m_standardTable);
        // 去重？？
        // for (int i = 0; i < m_valueLenth; ++i)
        //{
        //    m_eachColDataOfValue[i].toSet().toList();
        //}
        // qDebug() << "generateValueMatrix function ====================end ==============" << QTime::currentTime();
        return true;
    }

    void TextFileParser::FilterRows(vtkTable* table)
    {
        if (table->GetNumberOfRows() > 2)
        {
            table->RemoveRow(0);
            table->Modified();
            auto col0 = table->GetColumn(0);
            QString name = col0->GetName();
            name.replace(QRegExp("^\\s*#\\s*"), ""); // 将开头的 # 和空格替换为空字符串
            qDebug() << "name = " << name;
        }
    }

    void TextFileParser::UnitConversion(const QString& unit, double& value)
    {
        if (unit == "thz")
        {
            value /= 1E-6;
        }
        else if (unit == "ghz")
        {
            value /= 1E-3;
        }
        else if (unit == "khz")
        {
            value /= 1E3;
        }
        else if (unit == "hz")
        {
            value /= 1E6;
        }
        else if (unit == "ms")
        {
            value /= 1E-3;
        }
        else if (unit == "s")
        {
            value /= 1E-6;
        }
        else if (unit == "ns")
        {
            value /= 1E3;
        }
        else if (unit == "ps")
        {
            value /= 1E6;
        }
        else if (unit == "km")
        {
            value /= 1E-3;
        }
        else if (unit == "cm")
        {
            value /= 1E2;
        }
        else if (unit == "mm")
        {
            value /= 1E3;
        }
        else if (unit == "um")
        {
            value /= 1E6;
        }
        else if (unit == "mv/m")
        {
            value /= 1E3;
        }
        else if (unit == "ma/m")
        {
            value /= 1E3;
        }
        else if (unit == "mv")
        {
            value /= 1E3;
        }
        else if (unit == "a")
        {
            value /= 1E-3;
        }
    }

    void TextFileParser::UnitChange()
    {
        for (auto& unit : m_eachColUnitOfKey)
        {
            doUnitNameConversion(unit);
        }
        for (auto& unit : m_eachColUnitOfValue)
        {
            doUnitNameConversion(unit);
        }
    }

    void TextFileParser::changeMetaUnit(vtkTable* table)
    {
        for (int i = 0; i < table->GetNumberOfColumns(); i++)
        {
            auto col = table->GetColumn(i);
            TextArrayMetaStruct metaStruct;
            TextArrayMetaHander::getArrayMeta(col, metaStruct);
            auto& unit = metaStruct.unit;
            doUnitNameConversion(unit);
            TextArrayMetaHander::setArrayMeta(col, metaStruct);
        }
    }

    void TextFileParser::doUnitNameConversion(QString& unit)
    {
        unit = unit.trimmed();
        QString lowerUnit = unit.toLower();
        if (lowerUnit == "thz" || lowerUnit == "ghz" || lowerUnit == "khz" || lowerUnit == "hz")
        {
            unit = "MHz";
        }
        else if (lowerUnit == "ms" || lowerUnit == "s" || lowerUnit == "ns" || lowerUnit == "ps")
        {
            unit = "us";
        }
        else if (lowerUnit == "km" || lowerUnit == "cm" || lowerUnit == "mm" || lowerUnit == "um")
        {
            unit = "m";
        }
        else if (lowerUnit == "mv/m")
        {
            unit = "V/m";
        }
        else if (lowerUnit == "ma/m")
        {
            unit = "A/m";
        }
        else if (lowerUnit == "mv")
        {
            unit = "V";
        }
        else if (lowerUnit == "a")
        {
            unit = "mA";
        }
    }

    // bool TextFileParser::expandTable()
    //{
    //     QVector<QString> eachColNameOfKey;
    //     QVector<QString> eachColUnitOfKey;
    //     QVector<QString> eachColNameOfValue;
    //     QVector<QString> eachColUnitOfValue;
    //     if (!parseTitleName(m_originalTable, eachColNameOfKey, eachColUnitOfKey,
    //         eachColNameOfValue, eachColUnitOfValue))
    //     {
    //         return false;
    //     }

    //    // 先添加key列
    //    for (int i = 0; i < eachColNameOfKey.size(); i++)
    //    {
    //        auto array = m_originalTable->GetColumn(i);
    //        vtkNew<vtkDoubleArray> keyArray;
    //        keyArray->DeepCopy(array);
    //        m_expandedTable->AddColumn(keyArray);
    //    }

    //    // 处理value列
    //    if (m_fileDealType == 1) //
    //    {
    //        if (eachColNameOfValue.size() % 2 != 0)
    //        {
    //            qDebug() << "File format illegal! Value array must be even!";
    //            return false;
    //        }
    //        if (m_fileComponentType == 0) // 实部虚部模式
    //        {
    //            for (int i = 0; i < eachColNameOfValue.size(); i += 2)
    //            {
    //                auto realArray = vtkDoubleArray::SafeDownCast(m_originalTable->GetColumn(eachColNameOfKey.size() + i));
    //                auto imgArray = vtkDoubleArray::SafeDownCast(m_originalTable->GetColumn(eachColNameOfKey.size() + i + 1));

    //                auto realName = eachColNameOfValue[i];
    //                auto imgName = eachColNameOfValue[i + 1];

    //                QString commonName1;
    //                QString commonName2;
    //                bool isSuc1 = CommonFunction::extractContentBetweenParentheses(realName, commonName1);
    //                bool isSuc2 = CommonFunction::extractContentBetweenParentheses(imgName, commonName2);
    //                if (!isSuc1 || !isSuc2 || (commonName1 != commonName2))
    //                {
    //                    qDebug() << "Error! Col name not illegal.";
    //                    return false;
    //                }

    //                m_eachColGroupNameOfValue.append(commonName1);

    //                vtkNew<vtkDoubleArray> _realArray;
    //                vtkNew<vtkDoubleArray> _imgArray;
    //                _realArray->DeepCopy(realArray);
    //                _imgArray->DeepCopy(imgArray);

    //                vtkNew<vtkDoubleArray> _rArray;
    //                vtkNew<vtkDoubleArray> _thetaArray;
    //                QString rName = "r(" + commonName1 + ")" + "||" + eachColUnitOfValue[i] + "||value";
    //                QString thetaName = "theta(" + commonName1 + ")" + "||" + eachColUnitOfValue[i] + "||value";
    //                _rArray->SetName(rName.toUtf8().constData());
    //                _thetaArray->SetName(thetaName.toUtf8().constData());

    //                for (int j = 0; j < realArray->GetNumberOfTuples(); ++j)
    //                {
    //                    auto realValue = realArray->GetValue(j);
    //                    auto imgValue = imgArray->GetValue(j);

    //                    double r = qSqrt(realValue * realValue + imgValue * imgValue); // 计算幅度
    //                    double theta = qAtan2(imgValue, realValue);                    // 计算相位，使用 atan2 自动考虑 a 为负数的情况

    //                    _rArray->InsertNextValue(r);
    //                    _thetaArray->InsertNextValue(theta);
    //                }
    //                m_expandedTable->AddColumn(_rArray);
    //                m_expandedTable->AddColumn(_thetaArray);
    //                m_expandedTable->AddColumn(_realArray);
    //                m_expandedTable->AddColumn(_imgArray);
    //            }
    //            vtkNew<vtkDelimitedTextWriter> writer;
    //            writer->SetInputData(m_expandedTable);
    //            writer->SetFileName("D:/expandedTableRealImg.txt");
    //            writer->Write();
    //        }
    //        else if (m_fileComponentType == 1) // 幅度相位模式
    //        {
    //            for (int i = 0; i < eachColNameOfValue.size(); i += 2)
    //            {
    //                auto rArray = vtkDoubleArray::SafeDownCast(m_originalTable->GetColumn(eachColNameOfKey.size() + i));
    //                auto thetaArray = vtkDoubleArray::SafeDownCast(m_originalTable->GetColumn(eachColNameOfKey.size() + i + 1));

    //                auto rName = eachColNameOfValue[i];
    //                auto thetaName = eachColNameOfValue[i + 1];

    //                QString commonName1;
    //                QString commonName2;
    //                bool isSuc1 = CommonFunction::extractContentBetweenParentheses(rName, commonName1);
    //                bool isSuc2 = CommonFunction::extractContentBetweenParentheses(thetaName, commonName2);
    //                if (!isSuc1 || !isSuc2 || (commonName1 != commonName2))
    //                {
    //                    qDebug() << "Error! Col name not illegal.";
    //                    return false;
    //                }
    //                m_eachColGroupNameOfValue.append(commonName1);

    //                vtkNew<vtkDoubleArray> _rArray;
    //                vtkNew<vtkDoubleArray> _thetaArray;
    //                _rArray->DeepCopy(_rArray);
    //                _thetaArray->DeepCopy(thetaArray);

    //                vtkNew<vtkDoubleArray> _realArray;
    //                vtkNew<vtkDoubleArray> _imgArray;
    //                QString realName = "real(" + commonName1 + ")" + "||" + eachColUnitOfValue[i] + "||value";
    //                QString imgName = "img(" + commonName1 + ")" + "||" + eachColUnitOfValue[i] + "||value";
    //                _realArray->SetName(realName.toUtf8().constData());
    //                _imgArray->SetName(imgName.toUtf8().constData());

    //                for (int j = 0; j < rArray->GetNumberOfTuples(); ++j)
    //                {
    //                    auto rValue = rArray->GetValue(j);
    //                    auto thetaValue = thetaArray->GetValue(j);

    //                    auto realValue = rValue * qCos(thetaValue);
    //                    auto imgValue = rValue * qSin(thetaValue);

    //                    _realArray->InsertNextValue(realValue);
    //                    _imgArray->InsertNextValue(imgValue);
    //                }

    //                m_expandedTable->AddColumn(_rArray);
    //                m_expandedTable->AddColumn(_thetaArray);
    //                m_expandedTable->AddColumn(_realArray);
    //                m_expandedTable->AddColumn(_imgArray);
    //            }
    //            vtkNew<vtkDelimitedTextWriter> writer;
    //            writer->SetInputData(m_expandedTable);
    //            writer->SetFileName("D:/expandedTableRTheta.txt");
    //            writer->Write();
    //        }
    //    }
    //    else if (m_fileDealType == 2) // 增益文件处理
    //    {
    //        if (eachColNameOfValue.size() % 2 != 1)
    //        {
    //            qDebug() << "File format illegal! Value array must be odd!";
    //            return false;
    //        }

    //        if (m_fileComponentType == 0) // 实部虚部模式
    //        {
    //            for (int i = 0; i < eachColNameOfValue.size() - 1; i += 2) // 去除最后一个增益列
    //            {
    //                auto realArray = vtkDoubleArray::SafeDownCast(m_originalTable->GetColumn(eachColNameOfKey.size() + i));
    //                auto imgArray = vtkDoubleArray::SafeDownCast(m_originalTable->GetColumn(eachColNameOfKey.size() + i + 1));

    //                auto realName = eachColNameOfValue[i];
    //                auto imgName = eachColNameOfValue[i + 1];

    //                QString commonName1;
    //                QString commonName2;
    //                bool isSuc1 = CommonFunction::extractContentBetweenParentheses(realName, commonName1);
    //                bool isSuc2 = CommonFunction::extractContentBetweenParentheses(imgName, commonName2);

    //                if (!isSuc1 || !isSuc2 || (commonName1 != commonName2))
    //                {
    //                    qDebug() << "Error! Col name not illegal.";
    //                    return false;
    //                }

    //                m_eachColGroupNameOfValue.append(commonName1);

    //                vtkNew<vtkDoubleArray> _realArray;
    //                vtkNew<vtkDoubleArray> _imgArray;
    //                _realArray->DeepCopy(realArray);
    //                _imgArray->DeepCopy(imgArray);

    //                vtkNew<vtkDoubleArray> _rArray;
    //                vtkNew<vtkDoubleArray> _thetaArray;
    //                QString rName = "r(" + commonName1 + ")" + "||" + eachColUnitOfValue[i] + "||value";
    //                QString thetaName = "theta(" + commonName1 + ")" + "||" + eachColUnitOfValue[i] + "||value";
    //                _rArray->SetName(rName.toUtf8().constData());
    //                _thetaArray->SetName(thetaName.toUtf8().constData());

    //                for (int j = 0; j < realArray->GetNumberOfTuples(); ++j)
    //                {
    //                    auto realValue = realArray->GetValue(j);
    //                    auto imgValue = imgArray->GetValue(j);

    //                    double r = qSqrt(realValue * realValue + imgValue * imgValue); // 计算幅度
    //                    double theta = qAtan2(imgValue, realValue);                    // 计算相位，使用 atan2 自动考虑 a 为负数的情况

    //                    _rArray->InsertNextValue(r);
    //                    _thetaArray->InsertNextValue(theta);
    //                }

    //                m_expandedTable->AddColumn(_rArray);
    //                m_expandedTable->AddColumn(_thetaArray);
    //                m_expandedTable->AddColumn(_realArray);
    //                m_expandedTable->AddColumn(_imgArray);
    //            }

    //            vtkNew<vtkDoubleArray> _gainArray;
    //            _gainArray->DeepCopy(vtkDoubleArray::SafeDownCast(m_originalTable->GetColumn(eachColNameOfKey.size() + eachColNameOfValue.size() - 1)));
    //            m_expandedTable->AddColumn(_gainArray);

    //            vtkNew<vtkDelimitedTextWriter> writer;
    //            writer->SetInputData(m_expandedTable);
    //            writer->SetFileName("D:/expandedTableRealImgGain.txt");
    //            writer->Write();
    //        }
    //        else if (m_fileComponentType == 1) // 幅度相位模式
    //        {
    //            for (int i = 0; i < eachColNameOfValue.size() - 1; i += 2)
    //            {
    //                auto rArray = vtkDoubleArray::SafeDownCast(m_originalTable->GetColumn(eachColNameOfKey.size() + i));
    //                auto thetaArray = vtkDoubleArray::SafeDownCast(m_originalTable->GetColumn(eachColNameOfKey.size() + i + 1));

    //                auto rName = eachColNameOfValue[i];
    //                auto thetaName = eachColNameOfValue[i + 1];

    //                QString commonName1;
    //                QString commonName2;
    //                bool isSuc1 = CommonFunction::extractContentBetweenParentheses(rName, commonName1);
    //                bool isSuc2 = CommonFunction::extractContentBetweenParentheses(thetaName, commonName2);
    //                if (!isSuc1 || !isSuc2 || (commonName1 != commonName2))
    //                {
    //                    qDebug() << "Error! Col name not illegal.";
    //                    return false;
    //                }

    //                m_eachColGroupNameOfValue.append(commonName1);

    //                vtkNew<vtkDoubleArray> _rArray;
    //                vtkNew<vtkDoubleArray> _thetaArray;
    //                _rArray->DeepCopy(_rArray);
    //                _thetaArray->DeepCopy(thetaArray);

    //                vtkNew<vtkDoubleArray> _realArray;
    //                vtkNew<vtkDoubleArray> _imgArray;
    //                QString realName = "real(" + commonName1 + ")" + "||" + eachColUnitOfValue[i] + "||value";
    //                QString imgName = "img(" + commonName1 + ")" + "||" + eachColUnitOfValue[i] + "||value";
    //                _realArray->SetName(realName.toUtf8().constData());
    //                _imgArray->SetName(imgName.toUtf8().constData());

    //                for (int j = 0; j < rArray->GetNumberOfTuples(); ++j)
    //                {
    //                    auto rValue = rArray->GetValue(j);
    //                    auto thetaValue = thetaArray->GetValue(j);

    //                    auto realValue = rValue * qCos(thetaValue);
    //                    auto imgValue = rValue * qSin(thetaValue);

    //                    _realArray->InsertNextValue(realValue);
    //                    _imgArray->InsertNextValue(imgValue);
    //                }

    //                m_expandedTable->AddColumn(_rArray);
    //                m_expandedTable->AddColumn(_thetaArray);
    //                m_expandedTable->AddColumn(_realArray);
    //                m_expandedTable->AddColumn(_imgArray);
    //            }

    //            vtkNew<vtkDoubleArray> _gainArray;
    //            _gainArray->DeepCopy(vtkDoubleArray::SafeDownCast(m_originalTable->GetColumn(eachColNameOfKey.size() + eachColNameOfValue.size() - 1)));
    //            m_expandedTable->AddColumn(_gainArray);

    //            vtkNew<vtkDelimitedTextWriter> writer;
    //            writer->SetInputData(m_expandedTable);
    //            writer->SetFileName("D:/expandedTableRThetaGain.txt");
    //            writer->Write();
    //        }
    //    }

    //    // 添加注释列
    //    vtkStringArray* headCommentArray = vtkStringArray::SafeDownCast(m_originalTable->GetFieldData()->GetAbstractArray("HeadComment"));
    //    if (!headCommentArray || headCommentArray->GetNumberOfValues() == 0)
    //    {
    //        qDebug() << "m_originalTable has no ‘HeadComment’.";
    //    }
    //    QString headComment = QString::fromStdString(headCommentArray->GetValue(0));

    //    vtkNew<vtkStringArray> _headCommentArray;
    //    _headCommentArray->DeepCopy(headCommentArray);
    //    m_expandedTable->GetFieldData()->AddArray(_headCommentArray);

    //    // 添加标题列
    //    QString header{};
    //    for (int i = 0; i < m_expandedTable->GetNumberOfColumns(); ++i)
    //    {
    //        header += m_expandedTable->GetColumn(i)->GetName();
    //    }
    //    header = "#" + header;
    //    vtkNew<vtkStringArray> headerText;
    //    headerText->SetName("Header");
    //    headerText->SetNumberOfValues(1);
    //    headerText->SetValue(0, header.toUtf8().constData());
    //    m_originalTable->GetFieldData()->AddArray(headerText);
    //    return true;
    //}

    int TextFileParser::getRealValueIndex(int valueIndex, int componentIndex)
    {
        if (m_fileComponentType == 0) // componentIndex必须应该为0
        {
            return valueIndex;
        }
        // 其他情况valueIndex对应4列
        // return 4 * valueIndex + componentIndex;

        int realValueIndex = valueIndex;
        const auto& name = m_eachColGroupNameOfValue.at(valueIndex);

        for (int i = 0; i < m_originalTable->GetNumberOfColumns(); ++i)
        {
            auto colData = m_originalTable->GetColumn(i);

            TextArrayMetaStruct metaStruct;
            bool isSuc = TextArrayMetaHander::getArrayMeta(colData, metaStruct);
            if (!isSuc)
            {
                qDebug() << "获取meta失败";
                continue;
            }
            if (metaStruct.dataGroupName == name)
            {
                if (metaStruct.resultDataType == 4)
                {
                    realValueIndex = metaStruct.relatedScalarIndex;
                }
                else
                {
                    if (componentIndex == 0)
                    {
                        realValueIndex = metaStruct.relatedMagPartIndex;
                    }
                    else if (componentIndex == 1)
                    {
                        realValueIndex = metaStruct.relatedPhasePartIndex;
                    }
                    else if (componentIndex == 2)
                    {
                        realValueIndex = metaStruct.relatedRealPartIndex;
                    }
                    else if (componentIndex == 3)
                    {
                        realValueIndex = metaStruct.relatedImagPartIndex;
                    }
                }
                realValueIndex -= m_eachColNameOfKey.size();
                break;
            }
        }
        return realValueIndex;
    }

    QDomElement& TextFileParser::writeToProjectFile(QDomDocument* doc, QDomElement* element, bool isdiso)
    {
        QDomElement _TextFileParserRoot = doc->createElement("TextFileParser");
        GlobalHelperInstance->createDomElement(doc, &_TextFileParserRoot, "FileName", m_fileName);
        //大部分数据在读入text文件时已读入
        GlobalHelperInstance->createDomElement(doc, &_TextFileParserRoot, "ScanParaIndex", QString::number(m_scanParaIndex));
        GlobalHelperInstance->createDomElement(doc, &_TextFileParserRoot, "SecondScanParaIndex", QString::number(m_secondScanParaIndex));
        auto _chosenKeylistStr = GlobalHelperInstance->convertQVectorQVectorDoubleToQString(m_chosenKeyList);
        GlobalHelperInstance->createDomElement(doc, &_TextFileParserRoot, "ShosenKeyList", _chosenKeylistStr);
        element->appendChild(_TextFileParserRoot);
        return _TextFileParserRoot;
    }

    void TextFileParser::readFromProjectFile(QDomNodeList* nodelist, bool isdiso)
    {
        auto _element = nodelist->item(0).toElement();
        m_fileName = _element.elementsByTagName("FileName").item(0).toElement().text();
        auto isSuc = GlobalHelperInstance->CurrentInstallationDirectoryPathConversion(m_fileName);
        m_scanParaIndex = _element.elementsByTagName("ScanParaIndex").item(0).toElement().text().toInt();
        m_secondScanParaIndex = _element.elementsByTagName("SecondScanParaIndex").item(0).toElement().text().toInt();
        auto _chosenKeylistStr = _element.elementsByTagName("ShosenKeyList").item(0).toElement().text();
        m_chosenKeyList = GlobalHelperInstance->convertQStringToQVectorQVectorDouble(_chosenKeylistStr);
    }

} // namespace pst
